<template>
	<div>
		<el-dialog title="添加图片" width="1100px" :visible.sync="showPage" append-to-body>
			<el-form ref="addForm" :model="addForm" label-width="135px" style="height:auto">
				<el-form-item label="图片" prop="mainImage">
					<el-card style=" width: 180px; height: 180px;" shadow="hover">
						<el-image :src="addForm.localMainImage">
							<div slot="error" class="image-slot">
								<i>请上传图片</i>
							</div>
						</el-image>
					</el-card>
					
					<el-upload
						ref="uploadMainImage"
						:limit="1"
						:accept="'image/*'"
						list-type="picture"
						:show-file-list="false"
						:auto-upload="false"
						:headers="headerParams"
						:action="getUploadUrl()"
						:on-exceed="handleExceedMainImage"
						:on-change="imgPreviewMainImage"
						:on-success="handleSuccessMainImage"
						:on-error="handleErrorMainImage"
						:data="param"
					>
						<div style="margin-top: 20px;">
							<el-button slot="trigger" size="small" type="primary" @click="clickMainImageSelect">选取图片</el-button>
							<el-button style="margin-left: 10px;" size="small" type="success" @click.stop.prevent="submitUploadMainImage">上传到服务器
							</el-button>
						</div>
						<div>
							<el-button id="myImage" type="primary" icon="el-icon-folder-opened" @click.stop.prevent="showMyImageMain()">收藏夹</el-button>
							<el-button class="addMyImage" :class="{'addNotMyImage':mainImageCanCollecting}" type="primary" icon="el-icon-circle-plus-outline" :disabled="mainImageCanCollecting" @click.stop.prevent="addImageMain">添加收藏</el-button>
						</div>
						<div class="tips" slot="tip">只能上传jpg/png/jpeg文件</div>
					</el-upload>
				</el-form-item>
			</el-form>

			<div>
				<keep-alive>
					<chooseImagePage
						:choiseMainComponent="choiseMainComponent"
						@close-choose-image-page="closeChooseMainImagePage"
						@choosed-image="choosedMainImage"
					>
					</chooseImagePage>
				</keep-alive>
			</div>

			<div slot="footer" class="dialog-footer">
				<el-button type="primary" @click="submit">确 定</el-button>
				<el-button @click="cancel">取 消</el-button>
			</div>
		</el-dialog>
	</div>
</template>

<script>
	import util from '@/libs/util'
	import * as qiniu from 'qiniu-js'
	import { uploadImageUrl, getQiniuToken } from '@api/common/common'
	import chooseImagePage from '../system/sysImageFavorite/chooseImage'
	import { saveImage } from '@api/sysImageFavorite/sysImageFavorite'
	export default {
		name: 'uploadImage',
		components: {
			chooseImagePage
		},
		data() {
			return {
				showPage: false,
				result: '',
				typeValue: '',
				addForm: {
					mainImage: '',
					localMainImage: ''
				},
				param: {},
				choiseMainComponent: false,
				mainImageCanCollecting: true,

				headerParams: { // 上传图片的请求头
					client_id: '',
					democracy: ''
				},
				
				//七牛云参数
				file: '',
				qiniuKey: '',
				qiniuToken: '',
				qiniuPutExtra: {},
				qiniuConfig: {
					useCdnDomain: true,
					retryCount: 6,
				}
			}
		},
		props: {
			pageStatus: {
				type: Boolean
			},
			pageData: {
				type: '',
				default () {
					return {}
				}
			}
		},
		watch: {
			pageStatus(newValue) {
				this.showPage = newValue; //②监听外部对props属性 chkProd 的变更，并同步到组件内的data属性 showPage 中
			},
			showPage(newValue) {
				this.$emit('on-change', newValue); // ③组件内对 showPage 变更后向外部发送事件通知
			},
			result(newValue) {
				this.$emit('on-result', newValue); // ③组件内对 showPage 变更后向外部发送事件通知
			},
			pageData(value) {
				this.typeValue = value;
				if(!value) {
					this.resetParam();
				}
			},
		},
		methods: {
			cancel() {
				this.showPage = !this.showPage;
				if(this.showPage == false) {
					this.resetParam();
				}
				
			},
			handleClose(done) {
				this.$confirm('确定关闭吗').then(() => {
					// function(done)，done 用于关闭 Dialog
					this.resetParam()
					done()
				}).catch(() => {
					// console.log("点击确定时触发");
				})
			},
			resetParam() {
				// this.$refs['addForm'].resetFields();
				this.param = {}
				this.addForm = {
					mainImage: '',
					localMainImage: ''
				}
				this.$refs.uploadMainImage.clearFiles();
			},
			submit() {
				this.result = this.addForm
				this.showPage = !this.showPage
				this.resetParam()
			},

			/* 上传图片相关 BEGIN */
			getUploadUrl() {
				return uploadImageUrl()
			},
			imgPreviewMainImage(file, fileList) {
				let size = file.size;
				if(size > 1024*1024*2) {
					this.$message.error('图片大小不能超过2M！');
					fileList.splice(0);
					return;
				}
				
				let fileName = file.name
				let regex = /(.jpg|.jpeg|.png)$/
				if (regex.test(fileName.toLowerCase())) {
					this.addForm.localMainImage = URL.createObjectURL(file.raw)
				} else {
					this.$message.error('请选择图片文件')
					fileList.splice(0) //强行清空记录
				}
				this.file = file;
			},
			handleSuccessMainImage(response, file, fileList) {
				if (response.code == '000000') {
					this.$message.success('上传图片成功');
					this.addForm.mainImage = response.data.url;
					this.mainImageCanCollecting = false;
				} else {
					this.$message.error('上传图片失败:' + response.message)
					fileList.splice(0)
				}
			},
			handleErrorMainImage(err, file, fileList) {
				this.$message.error('上传失败,请重新上传图片!' + err)
				fileList.splice(0)
			},
			handleExceedMainImage(files, fileList) {
				this.$message.warning(`当前限制选择 1 个文件，本次选择了 ${files.length} 个文件，共选择了 ${files.length + fileList.length} 个文件`)
			},
			
			submitUploadMainImage() { //上传图片
				if (this.typeValue != '') {
					this.param.type = this.typeValue
					// this.$refs.uploadMainImage.submit();
					this.getQiniuToken()
				} else {
					this.$message.error('请选择图片类型')
				}
			},
			/* 上传图片相关 END */
			// 主图-添加到收藏夹
			addImageMain() {
				console.log('(addImageMain)this.mainImageCanCollecting=' + this.mainImageCanCollecting)
				// if(this.mainImageCanCollecting==true){
				//     this.$message({
				//         message: '请先上传图片到服务器',
				//         type: 'error'
				//     });
				//     return;
				// }
				this.$prompt('请输入图片描述', '添加图片到收藏夹', {
					confirmButtonText: '确定',
					cancelButtonText: '放弃收藏'
				})
				.then(value => {
					saveImage({
							imageUrl: this.addForm.mainImage,
							remark: value.value
						})
						.then((res) => {
							this.$message({
								message: '收藏成功',
								type: 'success',
							})
							this.mainImageCanCollecting = true;
							// this.fetchData();
							this.loading = false;
						})
						.catch((err) => {
							console.log('err', err);
							this.loading = false;
						});
				})
				.catch(() => {})
			},
			showMyImageMain() {
				this.choiseMainComponent = !this.choiseMainComponent;
			},
			closeChooseMainImagePage(val) {
				this.choiseMainComponent = val;
			},
			choosedMainImage(val) {
				this.addForm.mainImage = val.imageUrlSource;
				this.addForm.localMainImage = val.imageUrl;
				this.mainImageCanCollecting = true;
			},
			clickMainImageSelect() {
				this.mainImageCanCollecting = true;
			},
			
			getQiniuToken() {
				let name = this.file.name.split('.');
				let subffixName = '.' + name[name.length-1];
				
				getQiniuToken({subffixName: subffixName})
					.then(res => {
						this.qiniuToken = res.data.token;
						this.qiniuKey = res.data.key;
						this.uploadFile(this.file);
					})
			},
			uploadFile(file) {
				//qiniu.upload(file, key, token, putExtra, config)
				const observable = qiniu.upload(
					file.raw,
					this.qiniuKey,
					this.qiniuToken,
					this.qiniuPutExtra,
					this.qiniuConfig
				)
				
				// 上传开始
				observable.subscribe({
					next: res => {
						console.log(res)
					},
					error: err => {
						console.log(err)
						this.handleErrorMainImage(err, file)
					},
					complete: res => {
						console.log(res)
						this.$message.success('上传图片成功');
						this.addForm.mainImage = process.env.VUE_APP_OSS_DOMAIN + res.key;
						this.mainImageCanCollecting = false;
					},
				});
			},
		},
		mounted() {
			// 上传图片插件的请求头
			let getId = util.cookies.get('client')
			let client_id
			let getId2_reverse = getId.substring(0, 6)
			let getId2 = getId2_reverse.split('').reverse().join('') //后6位
			let getId1 = getId.substring(6, 13) //前7位
			client_id = 'client' + getId1 + getId2

			let democracy = util.cookies.get('democracy')

			this.headerParams.clientId = client_id
			this.headerParams.democracy = democracy
		}
	}
</script>

<style scoped lang="scss">
	#myImage {
		background-color: #6b116b;
		width: 80px;
		height: 32px;
		padding-top: 8px;
		padding-left: 8px;
		border-color: white;
	}

	.addMyImage {
		background-color: #b24cff;
		width: 104px;
		height: 32px;
		padding-top: 8px;
		padding-left: 12px;
		border: 0px solid white;
	}

	.addMyImage:hover {
		background-color: #b24cff;
	}

	.addNotMyImage {
		background-color: #ccc;
	}

	.addNotMyImage:hover {
		background-color: #ccc;
	}

	::v-deep .el-card__body {
		width: 100%;
		height: 100%;
	}

	.el-image {
		width: 100%;
		height: 100%;
	}

	::v-deep .image-slot {
		width: 100%;
		height: 100%;
		align-items: center;
		justify-content: center;
		display: flex;
	}

	.tips {
		line-height: normal;
		font-size: 14px;
		color: #f00;
		margin-top: 10px;
	}
</style>